package com.ada.shorurl;

import java.math.BigInteger;

public class Base62 {
    private static final String BASE62_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final BigInteger BASE = BigInteger.valueOf(BASE62_CHARACTERS.length());

    public static String encrypt(long number) {
        BigInteger value = BigInteger.valueOf(number);
        StringBuilder encrypted = new StringBuilder();

        while (value.compareTo(BigInteger.ZERO) > 0) {
            BigInteger remainder = value.mod(BASE);
            encrypted.insert(0, BASE62_CHARACTERS.charAt(remainder.intValue()));
            value = value.divide(BASE);
        }

        return encrypted.toString();
    }

    public static long decrypt(String encryptedNumber) {
        BigInteger value = BigInteger.ZERO;

        for (int i = encryptedNumber.length() - 1; i >= 0; i--) {
            char c = encryptedNumber.charAt(i);
            int digit = BASE62_CHARACTERS.indexOf(c);
            value = value.multiply(BASE).add(BigInteger.valueOf(digit));
        }

        return value.longValue();
    }

    public static void main(String[] args) {
        System.out.println(BASE62_CHARACTERS.length());
        long originalNumber = 123456789L;
        String encryptedNumber = encrypt(originalNumber);
        long decryptedNumber = decrypt(encryptedNumber);

        System.out.println("Original Number: " + originalNumber);
        System.out.println("Encrypted Number: " + encryptedNumber);
        System.out.println("Decrypted Number: " + decryptedNumber);
    }
}
